package org.dreamfly.dreamalarm.util;

import java.io.IOException;
import java.net.MalformedURLException;

import org.dreamfly.dreamalarm.DreamAlarmActivity;
import org.dreamfly.dreamalarm.FirendTellActivity;
import org.dreamfly.dreamalarm.R;
import org.dreamfly.dreamalarm.bean.User;
import org.dreamfly.dreamalarm.bean.WeiboBean;
import org.dreamfly.dreamalarm.bean.WeiboComments;

import com.google.gson.Gson;
import com.weibo.net.AccessToken;
import com.weibo.net.AsyncWeiboRunner;
import com.weibo.net.AsyncWeiboRunner.RequestListener;
import com.weibo.net.DialogError;
import com.weibo.net.Utility;
import com.weibo.net.Weibo;
import com.weibo.net.WeiboDialogListener;
import com.weibo.net.WeiboException;
import com.weibo.net.WeiboParameters;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

public class WeiboUtils {
	private static final String CONSUMER_KEY = "501673428";
	private static final String CONSUMER_SECRET = "69c21b293b072a8003feaac8d2c15b1e";
	private static WeiboUtils mWeiboUtilsInstance = null;

	private WeiboUtils() {

	}

	public synchronized static WeiboUtils getInstance() {
		if (mWeiboUtilsInstance == null) {
			return new WeiboUtils();
		} else {
			return mWeiboUtilsInstance;
		}
	}

	// -------------------------------------------------------------------------------
	// 发布微博
	// -------------------------------------------------------------------------------

	public boolean shareToWeiBo(String content, Context context) {
		Weibo weibo = Weibo.getInstance();
		weibo.setAccessToken(getLocalAccessToken(context));
		try {
			if (!TextUtils
					.isEmpty((String) (weibo.getAccessToken().getToken()))) {
				Log.d("WeiboUtils.accesstoken", weibo.getAccessToken()
						.getToken());
				update(context, weibo, CONSUMER_KEY, content, "", "");
			} else {
				//Toast.makeText(context,
				//		context.getString(R.string.please_login),
				//		Toast.LENGTH_LONG);
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (WeiboException e) {
			e.printStackTrace();
		}
		return true;
	}

	// -------------------------------------------------------------------------------
	// 获取微博评论
	// -------------------------------------------------------------------------------

	public boolean getWeiboComment(long id, Context context) {
		Weibo weibo = Weibo.getInstance();
		weibo.setAccessToken(getLocalAccessToken(context));
		try {
			if (!TextUtils
					.isEmpty((String) (weibo.getAccessToken().getToken()))) {
				showComment(context, weibo, CONSUMER_KEY, id);
			} else {
				Toast.makeText(context,
						context.getString(R.string.please_login),
						Toast.LENGTH_LONG);
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (WeiboException e) {
			e.printStackTrace();
		}
		return true;
	}

	// -------------------------------------------------------------------------------
	// 获取本地的accessToken
	// -------------------------------------------------------------------------------

	public AccessToken getLocalAccessToken(Context context) {
		SharedPreferences sharedata = context.getSharedPreferences(
				DreamAlarmActivity.SHAREPREFERENCE_DATA, 0);
		String access_token = sharedata.getString("access_token", "");
		long expires_in = sharedata.getLong("expires_in", 0);
		AccessToken accessToken = new AccessToken(access_token, CONSUMER_SECRET);
		accessToken.setExpiresIn(expires_in);
		return accessToken;
	}

	// -------------------------------------------------------------------------------
	// accessToken是否过期
	// -------------------------------------------------------------------------------

	public boolean isSessionValid(String accessToken, long expiresIn) {
		return (!TextUtils.isEmpty(accessToken) && (expiresIn == 0 || (System
				.currentTimeMillis() < expiresIn)));
	}

	// -------------------------------------------------------------------------------
	// 发表微博
	// -------------------------------------------------------------------------------

	public String update(final Context context, Weibo weibo, String source,
			String status, String lon, String lat)
			throws MalformedURLException, IOException, WeiboException {
		WeiboParameters bundle = new WeiboParameters();
		bundle.add("source", source);
		bundle.add("status", status);
		if (!TextUtils.isEmpty(lon)) {
			bundle.add("lon", lon);
		}
		if (!TextUtils.isEmpty(lat)) {
			bundle.add("lat", lat);
		}
		String rlt = "";
		String url = Weibo.SERVER + "statuses/update.json";
		
		Log.d("weibo utils update", weibo.getAccessToken().getToken());
		
		AsyncWeiboRunner weiboRunner = new AsyncWeiboRunner(weibo);
		weiboRunner.request(context, url, bundle, Utility.HTTPMETHOD_POST,
				new RequestListener() {
					// -------------------------------------------------------------------------------
					// 实现RequestListener接口的三个方法，负责发布后的逻辑，包括发布成功、遇到异常等
					// -------------------------------------------------------------------------------
					@Override
					public void onComplete(String response) {
						// TODO Auto-generated method stub
						Log.d("WeiboUtils.reponse", response);
						Log.d("WeiboUtils.id",
								String.valueOf(getWeiboId(response)));
						Editor sharedata = context.getSharedPreferences(
								DreamAlarmActivity.SHAREPREFERENCE_DATA, 0)
								.edit();
						sharedata.putLong("weibo_id", getWeiboId(response));
						sharedata.commit();
					}

					@Override
					public void onIOException(IOException e) {
						// TODO Auto-generated method stub
						Log.d("exception.io", e.getMessage());
					}

					@Override
					public void onError(WeiboException e) {
						// TODO Auto-generated method stub
						Log.d("exception.weibo", e.getStatusCode()+":"+e.getMessage());
					}

				});

		return rlt;
	}
	
	private static int commentCount=0;
	private static boolean addComment=false;
	
	public String showComment(Context context, Weibo weibo, String source,
			long id) throws MalformedURLException, IOException, WeiboException {
		WeiboParameters bundle = new WeiboParameters();
		bundle.add("source", source);
		bundle.add("id", String.valueOf(id));
		String rlt = "";
		String url = Weibo.SERVER + "comments/show.json";
		AsyncWeiboRunner weiboRunner = new AsyncWeiboRunner(weibo);
		final Context contextSend=context;
		weiboRunner.request(context, url, bundle, Utility.HTTPMETHOD_GET,
				new RequestListener() {
					// -------------------------------------------------------------------------------
					// 实现RequestListener接口的三个方法，负责发布后的逻辑，包括发布成功、遇到异常等
					// -------------------------------------------------------------------------------
					@Override
					public void onComplete(String response) {
						// TODO Auto-generated method stub
						Log.d("WeiboUtils.reponse", response);
						User user=getCommentUser(response);
						if (user != null && user.getName() != null) {
							Log.d("WeiboUtils.name", user.getName());
							if(WeiboUtils.addComment){
								clockRing(contextSend,user.getName());
								WeiboUtils.addComment=false;
							}
						} else {
							Log.d("WeiboUtils.name", "null");
						}
					}

					@Override
					public void onIOException(IOException e) {
						// TODO Auto-generated method stub
						Log.d("exception", e.getMessage());
					}

					@Override
					public void onError(WeiboException e) {
						// TODO Auto-generated method stub
						Log.d("exception", e.getMessage());
					}

				});

		return rlt;
	}

	private void clockRing(Context context,String name){
		Log.d("Comment", "Comment by "+name);
		Intent activityIntent=new Intent(context, FirendTellActivity.class);
		activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
		activityIntent.putExtra(FirendTellActivity.firendNameKey, name);
		context.startActivity(activityIntent);
	}
	
	// -------------------------------------------------------------------------------
	// 认证
	// -------------------------------------------------------------------------------

	public void goToAuthorize(Activity activity) {
		Weibo weibo = Weibo.getInstance();
		weibo.setupConsumerConfig(CONSUMER_KEY, CONSUMER_SECRET);
		weibo.setRedirectUrl("http://weibo.com/u/2154795684");
		weibo.authorize(activity, new AuthDialogListener(activity));
	}

	// -------------------------------------------------------------------------------
	// 获取刚发布的微博的id
	// -------------------------------------------------------------------------------

	public long getWeiboId(String responseString) {
		Gson gson = new Gson();
		WeiboBean weibo = gson.fromJson(responseString, WeiboBean.class);
		return weibo.getId();
	}
	
	// -------------------------------------------------------------------------------
	// 获取评论者的名字
	// -------------------------------------------------------------------------------

	public User getCommentUser(String responseString) {
		Gson gson = new Gson();
		WeiboComments comments = gson.fromJson(responseString,
				WeiboComments.class);
		Log.d("WeiboUtils getCommentUser", WeiboUtils.commentCount+" users:"+comments.getComments().size());
		//此处第一次判断不影响，会赋初值为0
		if(WeiboUtils.commentCount<comments.getComments().size()){
			WeiboUtils.addComment=true;
		}else{
			WeiboUtils.addComment=false;
		}
		WeiboUtils.commentCount=comments.getComments().size();
		if (comments.getComments().size() > 0) {
			return comments.getComments().get(0).getUser();
		} else {
			return null;
		}
	}

	// -------------------------------------------------------------------------------
	// 用户点击授权后的逻辑，包括授权成功、失败、取消和异常处理
	// -------------------------------------------------------------------------------

	class AuthDialogListener implements WeiboDialogListener {
		private Activity mActivity;

		public AuthDialogListener(Activity activity) {
			mActivity = activity;
		}

		@Override
		public void onComplete(Bundle values) {
			String token = values.getString("access_token");
			String expires_in = values.getString("expires_in");
			Editor sharedata = mActivity.getSharedPreferences(
					DreamAlarmActivity.SHAREPREFERENCE_DATA, 0).edit();
			sharedata.putString("access_token", token);
			long localExpires_in = System.currentTimeMillis()
					+ Integer.parseInt(expires_in) * 1000;
			sharedata.putLong("expires_in", localExpires_in);
			sharedata.putBoolean("isWeiboSharedOn", true);
			sharedata.commit();
			Log.d("WeiboUtils", "access_token : " + token + "  expires_in: "
					+ expires_in);
		}

		@Override
		public void onError(DialogError e) {
			Toast.makeText(mActivity.getApplicationContext(),
					"Auth error : " + e.getMessage(), Toast.LENGTH_LONG).show();
		}

		@Override
		public void onCancel() {
			Toast.makeText(mActivity.getApplicationContext(), "Auth cancel",
					Toast.LENGTH_LONG).show();
		}

		@Override
		public void onWeiboException(WeiboException e) {
			Toast.makeText(mActivity.getApplicationContext(),
					"Auth exception : " + e.getMessage(), Toast.LENGTH_LONG)
					.show();
		}

	}
}
